<template>
  <el-dialog
    :title="formTitle"
    :visible.sync="visible"
    width="600px"
    @close="handleClose">
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="120px">
      <#list table.columns as column>
        <#if !column.primary>
      <el-form-item label="${column.comment}" prop="${CodeGeneratorUtils.toCamelCase(column.name, false)}">
        <#if column.type == "text">
        <el-input
          type="textarea"
          v-model="formData.${CodeGeneratorUtils.toCamelCase(column.name, false)}"
          :rows="4"
          placeholder="请输入${column.comment}"
        />
        <#else>
        <el-input
          v-model="formData.${CodeGeneratorUtils.toCamelCase(column.name, false)}"
          placeholder="请输入${column.comment}"
        />
        </#if>
      </el-form-item>
        </#if>
      </#list>
    </el-form>

    <div slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { create${entityName}, update${entityName} } from '@/api/${lowEntityName}'

export default {
  name: '${entityName}Form',
  props: {
    visible: Boolean,
    data: Object,
    mode: {
      type: String,
      default: 'create' // 'create' or 'edit'
    }
  },
  data() {
    return {
      formData: this.initFormData(),
      formRules: {
        <#list table.columns as column>
          <#if !column.primary>
        ${CodeGeneratorUtils.toCamelCase(column.name, false)}: [
          { required: true, message: '${column.comment}不能为空', trigger: 'blur' }
        ]<#if column_has_next>,</#if>
          </#if>
        </#list>
      }
    }
  },
  computed: {
    formTitle() {
      return this.mode === 'create' ? '新增${table.comment}' : '编辑${table.comment}'
    }
  },
  watch: {
    data(newVal) {
      this.formData = this.initFormData(newVal)
    }
  },
  methods: {
    initFormData(data) {
      // 初始表单数据
      return {
        ...(data || {}),
        <#list table.columns as column>
        ${CodeGeneratorUtils.toCamelCase(column.name, false)}: data?.${CodeGeneratorUtils.toCamelCase(column.name, false)} || ''<#if column_has_next>,</#if>
        </#list>
      }
    },
    handleClose() {
      this.$emit('close')
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const request = this.mode === 'create'
            ? create${entityName}(this.formData)
            : update${entityName}(this.formData.id, this.formData)

          request
            .then(() => {
              this.$message.success('操作成功')
              this.$emit('success')
            })
        }
      })
    }
  }
}
</script>